﻿using System;
using System.Linq;
using System.Windows.Controls;
using System.Windows;
using System.Globalization;
using System.Threading;

namespace ForumsBrowser
{
    public class DateBlock : TextBlock
    {
        private Timer _timer;

        public DateBlock()
            : base()
        {
            this.Loaded += new RoutedEventHandler(DateBlock_Loaded);
            this.Unloaded += new RoutedEventHandler(DateBlock_Unloaded);
        }

        void DateBlock_Unloaded(object sender, RoutedEventArgs e)
        {
            if (_timer != null)
            {
                _timer.Dispose();
                _timer = null;
            }
        }

        void DateBlock_Loaded(object sender, RoutedEventArgs e)
        {
            if (AutoUpdate)
            {
                _timer = new Timer(Update, null, 60000, 60000);
            }
        }

        public static readonly DependencyProperty AutoUpdateProperty =
            DependencyProperty.Register("AutoUpdate", typeof(bool), typeof(DateBlock), new PropertyMetadata(false));

        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(DateTime), typeof(DateBlock), new PropertyMetadata(DateTime.Now, ValueChanged));

        private static readonly DateTimeTextConverter _converter = new DateTimeTextConverter();

        public DateTime Value
        {
            get { return (DateTime)this.GetValue(ValueProperty); }
            set 
            { 
                this.SetValue(ValueProperty, value);
            }
        }

        public bool AutoUpdate
        {
            get { return (bool)this.GetValue(AutoUpdateProperty); }
            set { this.SetValue(AutoUpdateProperty, value); }
        }

        public static void ValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            DateBlock block = sender as DateBlock;
            if (block != null && e.Property == ValueProperty)
            {
                block.Text = _converter.Convert(e.NewValue, typeof(DateTime), null, CultureInfo.CurrentCulture).ToString();
            }
        }

        public void Update(object arg)
        {
            if (this.Dispatcher.CheckAccess())
            {
                this.Text = _converter.Convert(Value, typeof(DateTime), null, CultureInfo.CurrentCulture).ToString();
            }
            else
            {
                this.Dispatcher.Invoke(new Action<object>(Update), arg);
            }
        }
    }
}
